import React, { createContext, useContext, useState, useEffect } from 'react';
import authService from '../services/authService';

/**
 * 认证上下文
 */
const AuthContext = createContext();

/**
 * 认证上下文提供者
 */
export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // 初始化用户状态
  useEffect(() => {
    const initializeAuth = async () => {
      try {
        // 检查本地存储的token和用户信息
        const token = localStorage.getItem('token');
        const userStr = localStorage.getItem('user');
        
        if (token && userStr) {
          const user = JSON.parse(userStr);
          setUser(user);
          setIsAuthenticated(true);
        } else {
          setUser(null);
          setIsAuthenticated(false);
        }
      } catch (error) {
        console.error('初始化认证状态失败:', error);
        setUser(null);
        setIsAuthenticated(false);
      } finally {
        setLoading(false);
      }
    };

    initializeAuth();
  }, []);

  /**
   * 登录
   */
  const login = async (username, password) => {
    try {
      const result = await authService.login({ username, password });
      
      if (result.success && result.data) {
        // 存储认证信息到localStorage
        localStorage.setItem('token', result.data.token);
        localStorage.setItem('user', JSON.stringify(result.data.user));
        
        // 更新状态
        setUser(result.data.user);
        setIsAuthenticated(true);
      }
      
      return result;
    } catch (error) {
      console.error('登录失败:', error);
      return {
        success: false,
        error: error.message || '登录失败'
      };
    }
  };

  /**
   * 登出
   */
  const logout = async () => {
    try {
      await authService.logout();
    } catch (error) {
      console.error('登出失败:', error);
    } finally {
      // 清理本地存储和状态
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      setUser(null);
      setIsAuthenticated(false);
    }
  };

  /**
   * 更新用户信息
   */
  const updateUser = (userData) => {
    const updatedUser = { ...user, ...userData };
    setUser(updatedUser);
    localStorage.setItem('user', JSON.stringify(updatedUser));
  };

  const value = {
    user,
    loading,
    isAuthenticated,
    login,
    logout,
    updateUser,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

/**
 * 使用认证上下文的Hook
 */
export const useAuth = () => {
  const context = useContext(AuthContext);
  
  if (!context) {
    throw new Error('useAuth 必须在 AuthProvider 内部使用');
  }
  
  return context;
};

export default AuthContext;